package com.beiding.render;

import java.util.ArrayList;
import java.util.List;

public class CoordinateUtils {

    public static String relativeToAbsolute(String relative, String path) {
        if (relative == null) {
            throw new RuntimeException("相对位置不能为空");
        }

        if (!relative.startsWith("/")) {
            throw new RuntimeException("错误的相对位置,需要使用'/'开始  " + relative);
        }

        String[] split = relative.split("/");
        List<String> segments = new ArrayList<>();

        for (int i = 1; i < split.length; i++) {
            if (split[i].trim().equals("")) {
                throw new RuntimeException("路径区段文本不能为空:" + relative);
            }
            segments.add(split[i]);
        }


        relativeToAbsolute(segments, path);

        StringBuilder builder = new StringBuilder();

        for (String segment : segments) {
            builder.append("/").append(segment);
        }

        return builder.toString();
    }


    private static void relativeToAbsolute(List<String> segments, String path) {

        if (path.equals("")) {
            return;
        }
        if (path.startsWith("/")) {
            segments.clear();
            String[] split = path.split("/");
            for (int i = 1; i < split.length; i++) {
                if (split[i].trim().equals("")) {
                    throw new RuntimeException("路径区段文本不能为空:" + path);
                }
                segments.add(split[i]);
            }
        } else if (path.startsWith("./")) {
            relativeToAbsolute(segments, path.substring(2));
        } else if (path.startsWith("../")) {

            if (segments.size() == 0) {
                throw new RuntimeException("错误的路径返回:" + path);
            }

            //移除最后一个
            segments.remove(segments.size() - 1);
            relativeToAbsolute(segments, path.substring(3));
        } else {

            //移除以为
            segments.remove(segments.size() - 1);
            String[] split = path.split("/");
            for (String aSplit : split) {
                if (aSplit.trim().equals("")) {
                    throw new RuntimeException("路径区段文本不能为空:" + path);
                }
                segments.add(aSplit);
            }
        }

    }

}
